package com.treasure.mall.zbqmallapi.resolver;

import com.treasure.mall.biz.entity.user.UserPO;
import com.treasure.mall.biz.service.core.user.UserService;
import com.treasure.mall.zbq.common.annotation.CurrentUser;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 *
 * +---------------------------------------------------------
 * * @package: com.treasure.mall.zbqmallapi.resolver
 * * @author: guomw (guomwchen@foxmail.com)
 * * @date: 2020/6/12 09:41
 * * @since: V1.0.0
 * +---------------------------------------------------------
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 * Copyright 2019-2022 com.treasure.mall.zbqmallapi.resolver Inc. All rights reserved.
 */
@AllArgsConstructor
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    private UserService userService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        if (parameter.hasParameterAnnotation(CurrentUser.class)) {
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest httpServletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
        if (httpServletRequest == null) {
            return null;
        }
//        String userID = request.getHeader("X-ID");
        String loginToken = httpServletRequest.getHeader("X-token");
        if (StringUtils.isNotBlank(loginToken)) {
            UserPO user = userService.findByToken(loginToken);
            if (user != null && user.getLoginToken().equals(loginToken)) {
                return user;
            }
        }
        return null;
    }

}
